from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework_jwt.views import api_settings
from rest_framework.generics import GenericAPIView

from .utils import OAuthQQ
from .models import OAuthQQUser
from . import serializers
from carts.utils import merge_cart_cookie_to_redis
# Create your views here.

# url(r'^qq/user/$', views.QQAuthUserView.as_view()),
class QQAuthUserView(GenericAPIView):
    """⽤户扫码登录的回调处理"""

    # 需要指定序列化器
    serializer_class = serializers.QQAuthUserSerializer

    def get(self, request):
            # 提取code请求参数
            code = request.query_params.get('code')
            if not code:
             return Response({'message':'缺少code'}, status=status.HTTP_400_BAD_REQUEST)
            # 实例化工具对象
            oauth = OAuthQQ()
            # 使⽤code向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)
            print(access_token)
            # 使⽤access_token向QQ服务器请求openid
            openid = oauth.get_openid(access_token)
            # 使⽤openid查询该QQ⽤户是否在美多商城中绑定过⽤户
            try:
                oauth_user = OAuthQQUser.objects.get(openid=openid)
            except OAuthQQUser.DoesNotExist:
                # 如果openid没绑定美多商城⽤户，创建⽤户并绑定到openid
                # 使用settings的SECRET_KEY结合itsdangerous模块，对openid进行签名后再响应给前端，为了保证安全
                access_token_openid = OAuthQQ.generate_save_user_token(openid)
                return Response({'access_token':access_token_openid})
            else:
                # 如果openid已绑定美多商城⽤户，直接⽣成JWT token，并返回
                user = oauth_user.user
                # 补充生成记录登录状态的token
                jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)
                # 先创建响应
                response = Response({
                    'token': token,
                    'user_id': user.id,
                    'username': user.username
                })
                response = merge_cart_cookie_to_redis(request=request, response=response, user=user)
                # 响应结果
                return response

    def post(self, request):
        """绑定用户到openid"""
        # 获取序列化器,并向序列化器内部传入POST请求发送过来的请求体
        serializer = self.get_serializer(data = request.data)
        # 开启校验
        serializer.is_valid(raise_exception=True)
        # 保存校验后的数据,开启校验后执行create方法返回user
        user = serializer.save()
        # 再次生成JWT_token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 先创建响应
        response = Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })
        response = merge_cart_cookie_to_redis(request=request, response=response, user=user)
        # 响应结果
        return response



#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    """提供QQ登录界面的URL"""
    def get(self, requset):
        # 获取next
        next = requset.query_params.get('next')
        # 获取url
        # 实例化工具对象
        oauth = OAuthQQ(state=next)
        # 调用工具类中获取qq扫码界面的url
        login_url = oauth.get_qq_login_url()
        # 将url返回给用户浏览器
        return Response({"login_url":login_url})
